package com.rr.handler;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

/**
 * @author RR
 * @date 2024/2/19 22:16
 */
@Component
public class ServiceSubscribeHandler implements ApplicationRunner {
    @NacosInjected
    private NamingService namingService;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    private static final String NACOS_PROVIDER_SERVICE = "nacosProvider";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        EventListener eventListener = event -> {
            if (event instanceof NamingEvent) {
                StringBuilder builder = new StringBuilder();
                builder.append(((NamingEvent) event).getServiceName()).append("上线，实例数").append(((NamingEvent) event).getInstances().size()).append("，实例详情：");
                for (Instance instance : ((NamingEvent) event).getInstances()) {
                    builder.append(instance.getIp()).append(":").append(instance.getPort()).append(";");
                }
                System.out.println(builder);
            }
        };
        namingService.subscribe(NACOS_PROVIDER_SERVICE, eventListener);
        System.out.println("订阅" + NACOS_PROVIDER_SERVICE + "成功");
    }
}
